package cn.passlink.www.Utils;
import cn.passlink.www.Enity.sysUser;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.UUID;
@Slf4j
public class JwtUtils {

    // 设置 token 过期时间(单位:毫秒)：目前为 12小时
    private static final long ttl = 43200000;
    // Signature 签名
    private static final String KEY = "df$554dt@#$56^%@@#$%^78";

    public static String createToken(sysUser user) {
        JwtBuilder jwtBuilder = Jwts.builder();

        return jwtBuilder
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setId(UUID.randomUUID().toString())
                .setSubject("Access Token")
                .setExpiration(new Date(System.currentTimeMillis() + ttl))
                .setIssuer("PASSLINK")
                .setIssuedAt(new Date())
                .claim("user_id", user.getUser_id())
                .claim("nickname", user.getNickname())
                .signWith(SignatureAlgorithm.HS256, KEY)
                .compact();
    }


    public static sysUser getClaims(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(KEY)
                    .parseClaimsJws(token)
                    .getBody();
            sysUser user =new sysUser();
            String userId = (String) claims.get("user_id");
            String nickname = (String) claims.get("nickname");
            user.setUser_id(userId);
            user.setNickname(nickname);
            System.out.println("User ID: " + userId);
            System.out.println("Nickname: " + nickname);
            return user;
        } catch (Exception e) {
            log.error("token 无效，无法解析",e);
            e.printStackTrace();
            return null;
        }
    }


    public static boolean isTokenExpired(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(KEY)
                    .parseClaimsJws(token)
                    .getBody();

            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (JwtException | IllegalArgumentException e) {
            log.error("token 过期", e);
           return true;
        }
    }


}
